package com.zzuli.fitness.controller;

import com.zzuli.fitness.entity.SysNotice;
import com.zzuli.fitness.service.SysNoticeService;
import com.zzuli.fitness.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "新闻接口")
@RestController
@RequestMapping("/sysNotice")
@Slf4j
public class SysNoticeController {
    @Autowired
    private SysNoticeService sysNoticeService;

    @ApiOperation(value = "查看所有新闻")
    @GetMapping("/findAllSysNotice")
    public Result findAllSysNotice(){
        List<SysNotice> list = sysNoticeService.selectAll();
        System.out.println(list);
        return Result.ok(list);
    }

    @ApiOperation(value = "查看新闻信息")
    @GetMapping("/findSysNoticeInfo")
    public Result findSysNoticeInfo(@RequestParam Integer id) {
        SysNotice sysNotice = sysNoticeService.selectNewsById(id);
        sysNotice.setNoticeContentText(getNoticeContentText(sysNotice.getNoticeContent()));
        List<String> img = getNoticeContentImages(sysNotice.getNoticeContent());
        if (img!=null){
            String url = "http://127.0.0.1:8090/fitness" + img.get(0);
            sysNotice.setNoticeContentImg(url);
        }
        return Result.ok(sysNotice);
    }

    private String getNoticeContentText(byte[] content) {
        if (content == null || content.length == 0) {
            return "";
        }
        try {
            String str = new String(content, "UTF-8");
            Document doc = Jsoup.parse(str);
            return doc.text();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    private List<String> getNoticeContentImages(byte[] content) {
        List<String> images = new ArrayList<>();
        if (content == null || content.length == 0) {
            return images;
        }
        try {
            String str = new String(content, "UTF-8");
            Document doc = Jsoup.parse(str);
            Elements imgElements = doc.select("img[src]");
            for (Element imgElement : imgElements) {
                images.add(imgElement.attr("src"));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return images;
    }
}
